package ui;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import logic.DriveLoader;
import logic.ModsLoader;

public class PanelLogin
{
	private JFrame					frmLogin;
	private JTextField			username;
	private JPasswordField	password;
	private JButton					login;

	/**
	 * Create the application.
	 */
	public PanelLogin()
	{
		initialize();
		frmLogin.setVisible(true);
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize()
	{
		frmLogin = new JFrame();
		frmLogin.setTitle("DkpManager: Google Login");
		frmLogin.setBounds(200, 200, 200, 300);
		frmLogin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		if (ModsLoader.lastGLoginName != null)
			username = new JTextField(ModsLoader.lastGLoginName);
		else
			username = new JTextField("Username");

		password = new JPasswordField("Password");
		login = new JButton("Google Login");

		frmLogin.setLayout(new GridLayout(3, 1, 30, 30));
		frmLogin.add(username);
		frmLogin.add(password);
		frmLogin.add(login);

		login.addActionListener(new ActionListener()
		{

			@Override
			public void actionPerformed(ActionEvent arg0)
			{
				System.out.println("Connection");
				if (!DriveLoader.getInstance().getAccess(username.getText(), new String(password.getPassword())))
				{
					JOptionPane.showMessageDialog(frmLogin, "Ereur de connection au compte google :(");
				}
				else if (!DriveLoader.getInstance().checkSpreadsheetUrl())
				{
					JOptionPane.showMessageDialog(frmLogin, "The google Spreadsheet configured is incorrect. Please check the address in config.txt file. See README.txt for more details.");
				}
				else
				{
					// dispose of this frame
					frmLogin.setVisible(false);
					frmLogin.dispose();

					// save login name for next time
					if (!username.getText().equals(ModsLoader.lastGLoginName))
						ModsLoader.getInstance().updateConfig(username.getText());

					// launch app
					new DkpManager();
				}

			}
		});

	}
}
